package com.learning.servlet2x.cookie;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * ClassName: CheckCookieServlet
 * Description: 永久登录-用于校验servlet
 * Date: 2018/6/24 13:03 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class CheckCookieServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    /**
     * 密钥, 可以放配置文件
     */
    private static final String KEY = ":https://sam-blog.gitee.io/";

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    /**
     * 校验
     */
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        boolean loggin = false;
        String account = null;
        String ssid = null;

        // 获取Cookie中的account与ssid
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            System.out.println("所有的Cookies : " + Arrays.asList(cookies));

            for (Cookie cookie : cookies) {
                if ((cookie.getName()).equals("account")) {
                    account = cookie.getValue();
                }
                if ((cookie.getName()).equals("ssid")) {
                    ssid = cookie.getValue();
                }
            }
        }

        if (account != null && ssid != null) {
            // 如果加密规则正确, 则视为已经登录.加密略
            loggin = ssid.equals(account + KEY);
        }

        System.out.println("是否匹配  :   " + loggin);
        request.getSession(true).setAttribute("login", loggin);

        // 跳转到登录页面
        request.getRequestDispatcher("/cookie/loginCookie.jsp").forward(request, response);
        return;
    }

}
